#!/bin/env python
# -*- coding: utf-8 -*-

import re
import sys
import os
import shutil
from pyinotify import *



cdn_dir = "/selinux/monitor/cdn"
vod_dir = "/selinux/monitor/vod"
out_dir = "/selinux/monitor/out"


class HandleLog(ProcessEvent):

	def process_IN_CLOSE_WRITE(self, event):
		handle_log(os.path.join(event.path,event.name))


def get_cdn_time(str):
	pattern = re.compile(r'_(\d{8})_(\d{6})_')
	r = pattern.search(str)
	if  r:
		return r.groups()[0]+r.groups()[1][:-2]
	else:
		return None

def get_vod_time(str):
	pattern = re.compile(r'_(\d{1,}).')
	r = pattern.search(str)
	if  r:
		return r.groups()[0]
	else:
		return None
	
def is_cdn_file(str):
	pattern = re.compile(r'access_cache_cache-')
	r = pattern.search(str)
	if r:
		return True
	else:
		return False


def is_vod_file(str):
	pattern = re.compile(r'onlineorder_')
	r = pattern.search(str)
	if r:
		return True
	else:
		return False

def find_cdn_file(dir):
	files = os.listdir(dir)
	files = filter(is_cdn_file,files)
	return files

def find_vod_file(dir):
	files = os.listdir(dir)
	files = filter(is_vod_file,files)
	return files


def deal_file(cdn,vod,out):
	try:
		fcdn = open(cdn,'r')
		fvod = open(vod,'r')
		fout = open(out,'w')	
	except Exception,e:
		print e
		sys.exit(1)
	
	fvod.close()
	for line1 in fcdn:
		data1 = line1.split("|")
		s = data1[14]
		fvod = open(vod,'r')
		for line2 in fvod:
			data2 = line2.split("|")
			t = data2[4]
			if s == t:
				if data2[7] == "0":
					data1[len(data1)-1] = "1\n"
				elif data2[7] == "1":
					data1[len(data1)-1] = "2\n"
				break
		fout.write("|".join(data1))
		fvod.close()
	fout.close()
	fcdn.close()

def handle_log(file):
	vod_files = find_vod_file(vod_dir)
	vod_times = map(get_vod_time,vod_files)
	print file
	print vod_files
	print vod_times
	


def init_check():
	if not os.path.isdir(cdn_dir) or  not os.path.isdir(vod_dir):
		print "%s or %s  not exsist" %(cdn_dir,vod_dir)
		sys.exit(1)


def monitor_cdn_log():
	wm= WatchManager() 
	mask= IN_CLOSE_WRITE
	notifier= Notifier(wm, HandleLog())
	wm.add_watch(cdn_dir,mask)
	while True:
		try:
			notifier.process_events()
			if notifier.check_events():
				notifier.read_events()
		except KeyboardInterrupt:
			notifier.stop()
			break

	

if __name__ == '__main__':
	
	init_check()
	print "start..."	
	monitor_cdn_log()



if not os.path.isdir(out_dir):
	print "create dir %s" %out_dir
	os.mkdir(out_dir)

for idx,cdn_file in enumerate(cdn_files):
	
	out_file = os.path.join(out_dir,"cdn_"+cdn_times[idx]+".log")
	cdn_file = os.path.join(cdn_dir,cdn_file)
	
	if cdn_times[idx] in vod_times:
		index = vod_times.index(cdn_times[idx])
		vod_file = os.path.join(vod_dir,vod_files[index])
		print "[do] %s <--> %s" %(cdn_file,vod_file)
		deal_file(cdn_file,vod_file,out_file)
	else:
		shutil.copyfile(cdn_file,out_file)

	print "[ok] %s ---> %s" %(cdn_file,out_file)


	 
